import json
import threading

from flask import Flask, render_template, Response, request, redirect
from flask_cors import CORS
from controller import EquipmentController, EquipmentTypeController, MasterController, EquipmentGroupController
from globalValues import GlobalVal
from service import EquipmentGroupService
import sql
from websocket_information import WebSocketController

app = Flask(__name__)
CORS(app, supports_credentials=True)
app.config['JSON_AS_ASCII'] = False
app.register_blueprint(EquipmentController.equipment, url_prefix='/equipment')
app.register_blueprint(EquipmentTypeController.equipmentType, url_prefix='/equipmentType')
app.register_blueprint(MasterController.master, url_prefix='/master')
app.register_blueprint(EquipmentGroupController.equipmentGroup, url_prefix='/equipmentGroup')


@app.route('/')
def hello_world():
    return redirect('/devices', code=301)
    # devices = sql.show_device()
    # types = sql.show_type()
    # groups = sql.show_groups_name()
    # td = dict(types)
    # gd = dict(groups)
    #
    # td2 = {value: key for key, value in td.items()}
    #
    # clist = sql.show_connection()
    # print(clist)
    # dlist = []
    # for d in devices:
    #     dlist.append((d[0], d[1]))
    # devices_dict = dict(dlist)
    #
    # # 日志
    # execution_logs = sql.show_executionLog_paging('', 0, 500)
    #
    # # 设备分组
    # glist = EquipmentGroupService.show_groups()
    #
    # return render_template('index2.html', devices=devices, connections=clist, td=td, devices_dict=devices_dict, td2=td2,
    #                        execution_logs=execution_logs, glist=glist, gd=gd)


@app.route('/devices')
def show_device():
    devices = sql.show_device()
    types = sql.show_type()
    groups = sql.show_groups_name()
    td = dict(types)

    td2 = {value: key for key, value in td.items()}

    clist = sql.show_connection()
    # print(clist)
    dlist = []
    for d in devices:
        dlist.append((d[0], d[1]))
    devices_dict = dict(dlist)

    return render_template('devices.html', devices=devices, connections=clist, td=td, devices_dict=devices_dict,
                           td2=td2)


@app.route('/add_device')
def add_dev():
    types = sql.show_type()
    td = dict(types)
    td2 = {value: key for key, value in td.items()}
    return render_template('add_device.html', td=td, td2=td2)


@app.route('/modify_device/<int:device_id>')
def modify_dev(device_id):
    dev = sql.get_device(device_id)
    types = sql.show_type()
    td = dict(types)
    device_name = dev[1]
    device_type = dev[2]
    device_addr = dev[3]
    td2 = {value: key for key, value in td.items()}
    return render_template('modify_device.html', device_id=device_id,
                           device_name=device_name, device_type=device_type,
                           device_addr=device_addr, td=td, td2=td2)


@app.route('/modify_device_interior/<int:device_id>')
def modify_device_interior(device_id):
    return render_template('modify_device_interior.html', device_id=device_id)


@app.route('/device_control/<int:device_id>')
def device_control(device_id):
    return render_template('device_control.html', device_id=device_id)


@app.route('/live_device/<int:device_id>')
def live_device(device_id):
    return render_template('live_device.html', device_id=device_id)


@app.route('/types')
def show_types():
    types = sql.show_type()
    td = dict(types)
    td2 = {value: key for key, value in td.items()}
    return render_template('types.html', td=td, td2=td2)


@app.route('/add_type')
def add_types():
    return render_template('add_type.html')


@app.route('/modify_type/<int:type_id>')
def modify_type(type_id):
    types = sql.show_type()
    td = dict(types)
    type_name = td[type_id]
    return render_template('modify_type.html', type_id=type_id, type_name=type_name)


@app.route('/conn')
def show_conn():
    devices = sql.show_device()
    clist = sql.show_connection()
    print(clist)
    groups = sql.show_groups_name()
    gd = dict(groups)
    dlist = []
    for d in devices:
        dlist.append((d[0], d[1]))
    devices_dict = dict(dlist)
    return render_template("connections.html", connections=clist, gd=gd, devices_dict=devices_dict)


@app.route('/add_conn')
def add_conn():
    devices = sql.show_device()
    groups = sql.show_groups_name()
    gd = dict(groups)
    dlist = []
    for d in devices:
        dlist.append((d[0], d[1]))
    devices_dict = dict(dlist)

    # 设备分组
    glist = EquipmentGroupService.show_groups()
    return render_template('add_conn.html', gd=gd, devices_dict=devices_dict, devices=devices, glist=glist)


@app.route('/log')
def show_log():
    # 日志
    execution_logs = sql.show_executionLog_paging('', 0, 500)

    return render_template('log.html', execution_logs=execution_logs)


@app.route('/groups')
def show_groups():
    # 设备分组
    glist = EquipmentGroupService.show_groups()
    print(glist)
    return render_template('groups.html', glist=glist)


@app.route('/add_group')
def add_group():
    devices = sql.show_device()
    return render_template('add_group.html', devices=devices)


@app.route('/modify_group/<int:group_id>')
def modify_group(group_id):
    g = sql.show_group_device_ids(group_id)[0]
    devices = sql.show_device()
    return render_template('modify_group.html', g=g, devices=devices)


@app.route('/test', methods=['GET', 'POST'])
def test():
    print(request.data)
    print('-' * 20)
    return "ok"


@app.route('/searchLog', methods=['GET', 'POST'])
def searchLog():
    search_text = json.loads(request.data)['search_text']
    execution_logs = sql.show_executionLog_paging(search_text, 0, 500)
    show_executionLog_paging = {'show_executionLog_paging': execution_logs}

    return show_executionLog_paging


@app.route('/modify_conn/<int:conn_id>')
def modify_conn(conn_id):
    devices = sql.show_device()
    types = sql.show_type()
    groups = sql.show_groups_name()
    td = dict(types)
    gd = dict(groups)

    td2 = {value: key for key, value in td.items()}

    clist = sql.show_connection()
    print(clist)
    dlist = []
    for d in devices:
        dlist.append((d[0], d[1]))
    devices_dict = dict(dlist)
    connection = sql.get_connection_info(conn_id)

    # 设备分组
    glist = EquipmentGroupService.show_groups()

    return render_template('modify_conn.html', devices=devices, connection=connection, td=td, devices_dict=devices_dict,
                           td2=td2,
                           glist=glist, gd=gd)


@app.route('/brainMap')
def brainMap():
    return render_template('brainMap.html')


def reverse_type(type_num, type_list):
    for i in type_list:
        if i[0] == type_num:
            return i[1]


if __name__ == '__main__':
    GlobalVal.websocket_future = GlobalVal.pool.submit(WebSocketController.configWS)
    app.run(host='127.0.0.1', port=4000)
